import streamlit as st
from streamlit_echarts import st_echarts
import pandas as pd

# 读取CSV数据
# 原代码：data = pd.read_csv('拉勾网2223招聘数据.csv')
# 修改后：
data = pd.read_csv('拉勾网2023招聘数据.csv')  # 与job_analysis_app.py统一

# 处理薪资数据
def parse_salary(salary_str):
    if '-' in salary_str:
        low, high = salary_str.lower().replace('k', '').split('-')
        return (float(low) + float(high)) / 2 * 1000
    else:
        return None

data['salary_mid'] = data['salary'].apply(parse_salary)

# 添加图表类型选择器
region_chart_type = st.sidebar.selectbox('地区图表类型', ['柱状图', '折线图', '饼图'])
salary_chart_type = st.sidebar.selectbox('薪资图表类型', ['柱状图', '折线图', '散点图', '雷达图'])
position_chart_type = st.sidebar.selectbox('岗位图表类型', ['柱状图', '折线图', '饼图', '散点图'])

# 添加5个新的可视化问题选择器
analysis_question = st.sidebar.selectbox('选择分析问题', [
    '1. 不同工作经验对应的薪资分布',
    '2. 公司规模与薪资水平的关系',
    '3. 公司发展阶段与薪资关系',
    '4. 不同公司福利与薪资的关系',
    '5. 不同城市薪资水平对比'
])

# 添加城市和岗位选择器
selected_city = st.sidebar.selectbox('选择城市', ['全部'] + data['city'].unique().tolist())
selected_position = st.sidebar.selectbox('选择岗位', ['全部'] + data['positionName'].unique().tolist())

# 添加薪资范围选择器
salary_range = st.sidebar.slider(
    '选择薪资范围(元)', 
    min_value=int(data['salary_mid'].min()), 
    max_value=int(data['salary_mid'].max()), 
    value=(int(data['salary_mid'].min()), int(data['salary_mid'].max()))
)

# 添加工作经验选择器
work_experience = st.sidebar.selectbox('选择工作经验', ['全部'] + data['workYear'].unique().tolist())

# 添加学历要求选择器
education_requirement = st.sidebar.selectbox('选择学历要求', ['全部'] + data['education'].unique().tolist())

# 1. 地区分布图表
region_option = {
    "title": {"text": '地区分布'},
    "tooltip": {
        "trigger": 'item',
        "formatter": '{a}<br/>{b}: {c}个职位 ({d}%)'
    },
    "xAxis": {
        "type": 'category',
        "data": data['city'].value_counts().head(10).index.tolist()
    },
    "yAxis": {},
    "series": [
        {
            "name": '职位数量',
            "type": 'bar' if region_chart_type == '柱状图' else 'line' if region_chart_type == '折线图' else 'pie',
            "data": data['city'].value_counts().head(10).tolist(),
            "label": {
                "show": True,
                "formatter": '{b}: {c} ({d}%)',
                "position": 'outside',
                "fontSize": 12,
                "fontWeight": 'bold',
                "emphasis": {
                    "show": True,
                    "fontSize": 14,
                    "fontWeight": 'bold'
                }
            },
            "emphasis": {
                "itemStyle": {
                    "shadowBlur": 10,
                    "shadowOffsetX": 0,
                    "shadowColor": 'rgba(0, 0, 0, 0.5)'
                },
                "label": {
                    "show": True
                }
            }
        }
    ]
}

if region_chart_type == '饼图':
    region_option['series'][0]['radius'] = '50%'
    region_option['series'][0]['center'] = ['50%', '50%']

# 2. 薪资分布图表
salary_option = {
    "title": {
        "text": '薪资分布',
        "subtext": '数据来自拉勾网',
        "left": 'center'
    },
    "tooltip": {
        "trigger": 'axis',
        "axisPointer": {
            "type": 'cross',
            "crossStyle": {
                "color": '#999'
            }
        }
    },
    "legend": {
        "data": ['岗位数量', '平均薪资'],
        "left": 'right'
    },
    "xAxis": {
        "type": 'category',
        "data": ['<10k', '10-20k', '20-30k', '30-40k', '>40k'],
        "axisPointer": {
            "type": 'shadow'
        }
    },
    "yAxis": [
        {
            "type": 'value',
            "name": '岗位数量',
            "min": 0,
            "axisLabel": {
                "formatter": '{value}'
            }
        },
        {
            "type": 'value',
            "name": '平均薪资',
            "min": 0,
            "axisLabel": {
                "formatter": '{value}元'
            }
        }
    ],
    "series": [
        {
            "name": '岗位数量',
            "type": 'line' if salary_chart_type == '折线图' else 'bar' if salary_chart_type == '柱状图' else 'pie',
            "data": [
                len(data[data['salary_mid'] < 10000]),
                len(data[(data['salary_mid'] >= 10000) & (data['salary_mid'] < 20000)]),
                len(data[(data['salary_mid'] >= 20000) & (data['salary_mid'] < 30000)]),
                len(data[(data['salary_mid'] >= 30000) & (data['salary_mid'] < 40000)]),
                len(data[data['salary_mid'] >= 40000])
            ],
            "itemStyle": {
                "color": '#5470C6'
            }
        },
        {
            "name": '平均薪资',
            "type": 'line' if salary_chart_type == '折线图' else 'bar' if salary_chart_type == '柱状图' else 'pie',
            "yAxisIndex": 1,
            "data": [
                data[data['salary_mid'] < 10000]['salary_mid'].mean(),
                data[(data['salary_mid'] >= 10000) & (data['salary_mid'] < 20000)]['salary_mid'].mean(),
                data[(data['salary_mid'] >= 20000) & (data['salary_mid'] < 30000)]['salary_mid'].mean(),
                data[(data['salary_mid'] >= 30000) & (data['salary_mid'] < 40000)]['salary_mid'].mean(),
                data[data['salary_mid'] >= 40000]['salary_mid'].mean()
            ],
            "itemStyle": {
                "color": '#EE6666'
            }
        }
    ]
}


if salary_chart_type == '箱型图':
    salary_option['series'][0]['type'] = 'boxplot'
    salary_option['series'][1]['type'] = 'boxplot'
elif salary_chart_type == '热力图':
    salary_option['series'][0]['type'] = 'heatmap'
    salary_option['series'][1]['type'] = 'heatmap'
elif salary_chart_type == '散点图':
    salary_option['series'][0]['type'] = 'scatter'
    salary_option['series'][1]['type'] = 'scatter'
elif salary_chart_type == '雷达图':
    # 创建雷达图数据
    radar_data = [
        {
            'name': '岗位数量',
            'value': [
                len(data[data['salary_mid'] < 10000]),
                len(data[(data['salary_mid'] >= 10000) & (data['salary_mid'] < 20000)]),
                len(data[(data['salary_mid'] >= 20000) & (data['salary_mid'] < 30000)]),
                len(data[(data['salary_mid'] >= 30000) & (data['salary_mid'] < 40000)]),
                len(data[data['salary_mid'] >= 40000])
            ],
            'itemStyle': {'color': '#5470C6'}
        },
        {
            'name': '平均薪资',
            'value': [
                data[data['salary_mid'] < 10000]['salary_mid'].mean(),
                data[(data['salary_mid'] >= 10000) & (data['salary_mid'] < 20000)]['salary_mid'].mean(),
                data[(data['salary_mid'] >= 20000) & (data['salary_mid'] < 30000)]['salary_mid'].mean(),
                data[(data['salary_mid'] >= 30000) & (data['salary_mid'] < 40000)]['salary_mid'].mean(),
                data[data['salary_mid'] >= 40000]['salary_mid'].mean()
            ],
            'itemStyle': {'color': '#EE6666'}
        }
    ]
    
    # 更新为雷达图配置
    salary_option = {
        'title': {'text': '薪资分布雷达图', 'left': 'center'},
        'tooltip': {'trigger': 'item'},
        'legend': {'data': ['岗位数量', '平均薪资'], 'left': 'right'},
        'radar': {
            'indicator': [
                {'name': '<10k', 'max': max([d['value'][0] for d in radar_data]) * 1.2},
                {'name': '10-20k', 'max': max([d['value'][1] for d in radar_data]) * 1.2},
                {'name': '20-30k', 'max': max([d['value'][2] for d in radar_data]) * 1.2},
                {'name': '30-40k', 'max': max([d['value'][3] for d in radar_data]) * 1.2},
                {'name': '>40k', 'max': max([d['value'][4] for d in radar_data]) * 1.2}
            ]
        },
        'series': [{
            'name': '薪资分布',
            'type': 'radar',
            'data': radar_data
        }]
    }

# 3. 学历和工作经验分布图表
position_option = {
    "title": {"text": '学历和工作经验分布'},
    "tooltip": {},
    "legend": {
        "data": ['学历分布', '工作经验分布'],
        "top": 'bottom'
    },
    "xAxis": {
        "type": 'category',
        "data": data['education'].value_counts().index.tolist()
    },
    "yAxis": {
        "type": 'value'
    },
    "series": [
        {
            "name": '学历分布',
            "type": 'bar' if position_chart_type == '柱状图' else 'line' if position_chart_type == '折线图' else 'pie',
            "data": data['education'].value_counts().tolist(),
            "itemStyle": {
                "color": '#5470C6'
            }
        },
        {
            "name": '工作经验分布',
            "type": 'line' if position_chart_type == '折线图' else 'bar' if position_chart_type == '柱状图' else 'pie',
            "data": data['workYear'].value_counts().tolist(),
            "itemStyle": {
                "color": '#EE6666'
            }
        }
    ]
}

if position_chart_type == '饼图':
    position_option['series'][0]['radius'] = '50%'
    position_option['series'][0]['center'] = ['50%', '50%']
    position_option['series'][1]['radius'] = '50%'
    position_option['series'][1]['center'] = ['50%', '50%']
elif position_chart_type == '热力图':
    position_option['series'][0]['type'] = 'heatmap'
    position_option['series'][1]['type'] = 'heatmap'
elif position_chart_type == '散点图':
    position_option['series'][0]['type'] = 'scatter'
    position_option['series'][1]['type'] = 'scatter'



# 根据选择过滤数据
if selected_city != '全部' and selected_position != '全部':
    filtered_data = data[(data['city'] == selected_city) & (data['positionName'] == selected_position)]
elif selected_city != '全部':
    filtered_data = data[data['city'] == selected_city]
elif selected_position != '全部':
    filtered_data = data[data['positionName'] == selected_position]
else:
    filtered_data = data

# 应用薪资范围过滤
filtered_data = filtered_data[
    (filtered_data['salary_mid'] >= salary_range[0]) & 
    (filtered_data['salary_mid'] <= salary_range[1])
]

# 应用工作经验过滤
if work_experience != '全部':
    filtered_data = filtered_data[filtered_data['workYear'] == work_experience]
    
# 应用学历要求过滤
if education_requirement != '全部':
    filtered_data = filtered_data[filtered_data['education'] == education_requirement]

# 更新图表数据
region_option['xAxis']['data'] = filtered_data['city'].value_counts().head(10).index.tolist()
region_option['series'][0]['data'] = filtered_data['city'].value_counts().head(10).tolist()

salary_option['series'][0]['data'] = [
    len(filtered_data[filtered_data['salary_mid'] < 10000]),
    len(filtered_data[(filtered_data['salary_mid'] >= 10000) & (filtered_data['salary_mid'] < 20000)]),
    len(filtered_data[(filtered_data['salary_mid'] >= 20000) & (filtered_data['salary_mid'] < 30000)]),
    len(filtered_data[(filtered_data['salary_mid'] >= 30000) & (filtered_data['salary_mid'] < 40000)]),
    len(filtered_data[filtered_data['salary_mid'] >= 40000])
]

if selected_position != '全部':
    position_option['yAxis']['data'] = [selected_position]
    position_option['series'][0]['data'] = [len(filtered_data)]
    position_option['series'][0]['barWidth'] = 10  # 设置细长柱状图
else:
    position_option['yAxis']['data'] = filtered_data['positionName'].value_counts().head(10).index.tolist()
    position_option['series'][0]['data'] = filtered_data['positionName'].value_counts().head(10).tolist()
    position_option['series'][0]['barWidth'] = 20  # 默认宽度

# 显示图表
st.title('拉勾网招聘数据可视化')

# 根据选择的问题显示不同的分析结果
if analysis_question == '1. 不同工作经验对应的薪资分布':
    st.subheader('不同工作经验对应的薪资分布')
    
    # 按工作经验分组计算薪资
    work_year_salary = data.groupby('workYear')['salary_mid'].agg(['mean', 'count']).reset_index()
    
    # 创建图表选项
    work_year_option = {
        "title": {"text": '工作经验与薪资关系'},
        "tooltip": {"trigger": 'axis'},
        "xAxis": {"type": 'category', "data": work_year_salary['workYear'].tolist()},
        "yAxis": {"type": 'value', "name": '平均薪资(元)'},
        "series": [{
            "name": '平均薪资',
            "type": 'bar',
            "data": work_year_salary['mean'].tolist(),
            "itemStyle": {"color": '#5470C6'}
        }]
    }
    st_echarts(options=work_year_option, height='400px')
    

elif analysis_question == '2. 公司规模与薪资水平的关系':
    st.subheader('公司规模与薪资水平的关系')
    
    # 按公司规模分组计算薪资
    company_size_salary = data.groupby('companySize')['salary_mid'].agg(['mean', 'count']).reset_index()
    
    # 创建雷达图选项
    radar_option = {
        "title": {"text": '公司规模与薪资关系'},
        "tooltip": {},
        "radar": {
            "indicator": [
                {"name": size, "max": company_size_salary['mean'].max() * 1.2}
                for size in company_size_salary['companySize']
            ]
        },
        "series": [{
            "name": '平均薪资',
            "type": 'radar',
            "data": [{
                "value": company_size_salary['mean'].tolist(),
                "name": '平均薪资',
                "areaStyle": {"color": 'rgba(84, 112, 198, 0.5)'}
            }]
        }]
    }
    st_echarts(options=radar_option, height='500px')
    
elif analysis_question == '4. 不同公司福利与薪资的关系':
    st.subheader('不同公司福利与薪资的关系')
    
    # 提取常见福利关键词
    benefit_keywords = ['五险一金', '带薪年假', '弹性工作', '年终奖', '补充医疗保险', '餐补', '交通补助', '股票期权']
    
    # 分析福利与薪资的关系
    benefit_salary = {}
    for benefit in benefit_keywords:
        benefit_salary[benefit] = data[data['positionDetail'].str.contains(benefit)]['salary_mid'].mean()
    
    # 创建图表选项
    benefit_option = {
        "title": {"text": '公司福利与薪资关系'},
        "tooltip": {"trigger": 'axis'},
        "xAxis": {"type": 'category', "data": benefit_keywords},
        "yAxis": {"type": 'value', "name": '平均薪资(元)'},
        "series": [{
            "name": '平均薪资',
            "type": 'bar',
            "data": [benefit_salary[benefit] for benefit in benefit_keywords],
            "itemStyle": {"color": '#91CC75'}
        }]
    }
    st_echarts(options=benefit_option, height='400px')
    
elif analysis_question == '5. 不同城市薪资水平对比':
    st.subheader('不同城市薪资水平对比')
    
    # 按城市分组计算薪资
    city_salary = data.groupby('city')['salary_mid'].mean().sort_values(ascending=False).head(10)
    
    # 创建图表选项
    city_option = {
        "title": {"text": '城市薪资对比'},
        "tooltip": {"trigger": 'axis'},
        "xAxis": {"type": 'category', "data": city_salary.index.tolist()},
        "yAxis": {"type": 'value', "name": '平均薪资(元)'},
        "series": [{
            "name": '平均薪资',
            "type": 'bar',
            "data": city_salary.tolist(),
            "itemStyle": {"color": '#EE6666'}
        }]
    }
    st_echarts(options=city_option, height='400px')
    
    
elif analysis_question == '3. 公司发展阶段与薪资关系':
    st.subheader('公司发展阶段与薪资关系')
    
    # 按公司发展阶段分组计算薪资
    finance_stage_salary = data.groupby('financeStage')['salary_mid'].agg(['mean', 'count']).reset_index()
    
    # 创建折线图选项
    line_option = {
        "title": {"text": '公司发展阶段与薪资关系'},
        "tooltip": {"trigger": 'axis'},
        "legend": {"data": ['平均薪资', '岗位数量']},
        "xAxis": {"type": 'category', "data": finance_stage_salary['financeStage'].tolist()},
        "yAxis": [
            {"type": 'value', "name": '平均薪资(元)'},
            {"type": 'value', "name": '岗位数量'}
        ],
        "series": [
            {
                "name": '平均薪资',
                "type": 'line',
                "data": finance_stage_salary['mean'].tolist(),
                "itemStyle": {"color": '#5470C6'}
            },
            {
                "name": '岗位数量',
                "type": 'bar',
                "yAxisIndex": 1,
                "data": finance_stage_salary['count'].tolist(),
                "itemStyle": {"color": '#91CC75'}
            }
        ]
    }
    st_echarts(options=line_option, height='500px')
    
# 显示基础图表
st.subheader('地区分布')
st_echarts(options=region_option, height='400px')

st.subheader('薪资分布')
st_echarts(options=salary_option, height='400px')

st.subheader('岗位分布')
st_echarts(options=position_option, height='400px')